//
//  AppDelegate.m
//  AqualPolo
//
//  Created by dong on 2024/5/1.
//

#import "AppDelegate.h"
#import "APTabBarViewController.h"
#import "APLoginViewController.h"
#import "APGuideViewController.h"
#import "APLoginManager.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = UIColor.whiteColor;
    [IQKeyboardManager sharedManager].enable = true;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = true;
    [IQKeyboardManager sharedManager].enableAutoToolbar = false;
    NSUserDefaults *userdefault = [NSUserDefaults standardUserDefaults];
    NSString *isFirstLaunch = [userdefault objectForKey:@"isFirstLaunch"];
    if (!isFirstLaunch || ![isFirstLaunch isEqualToString:@"NO"]) {
        [userdefault setObject:@"NO" forKey:@"isFirstLaunch"];
        self.window.rootViewController = [[APGuideViewController alloc] init];
    }else{
        bool isLogin = [[APLoginManager shareInstance] isLogin];
        if (isLogin) {
            self.window.rootViewController = [[APTabBarViewController alloc]init];
            [self checkToken];
        }else{
            self.window.rootViewController = [[APLoginViewController alloc] init];
        }
    }
    [self.window makeKeyAndVisible];
    [APLogManager statisticWithPage:APPage_launch];
    return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application{
    [self requestIDFA];
}

- (void)checkToken{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    NSString *token = [[APLoginManager shareInstance] token];
    [parameters setNullObject:token forKey:@"token"];
    [self.window ShowProgress];
    [APDataManager postJsonWithUrlString:ValidToken_URL timeoutInterval:20 parameters:parameters result:^(NSDictionary * _Nullable res) {
        [self.window removeProgress];
    } failBlock:^(NSString * _Nullable errorMsg) {
        [self.window ShowProgressOnlyLabel:errorMsg];
        if (![self.window.rootViewController isKindOfClass:[APLoginViewController class]]) {
            self.window.rootViewController  = [[APLoginViewController alloc] init];
        }
    }];
}

- (void)requestIDFA {
    if (@available(iOS 14, *)) {
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {}];
    }
}


@end
